<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>14-键盘事件练习</title>
    <style>
        #box1 {
            width: 100px;
            height: 100px;
            background-color: #bfa;
            position: absolute;
        }
    </style>

    <script>

        window.onload = function () {

            document.onkeydown = function (event) {

                event = event || window.event;

                // console.log(event.keyCode);

                var box1 = document.getElementById("box1");

                var speed = 10;

                //按了ctrl以后速度加快
                if (event.ctrlKey) {
                    var speed = 50;
                }

                if (event.keyCode == 37) {
                    //向左
                    box1.style.left = box1.offsetLeft - speed + "px";
                } else if (event.keyCode == 38) {
                    //向上
                    box1.style.top = box1.offsetTop - speed + "px";
                } else if (event.keyCode == 39) {
                    //向右
                    box1.style.left = box1.offsetLeft + speed + "px";
                } else if (event.keyCode == 40) {
                    //向下
                    box1.style.top = box1.offsetTop + speed + "px";
                } else {
                    box1.style.top = box1.offsetTop + speed + "px";
                }
            }
        }


    </script>
</head>

<body>
    <div id="box1"></div>
</body>

</html>